<template>
    <el-dialog title="图片库" :visible.sync="show" :close-on-click-modal="false" @close="onClose">
		<section class="upload-box _display_flex">
            <!-- 分组 -->
			<div class="upload-mkdir">
                <div class="mkdir-item _display_flex" @click="switchMkdir(-1, '全部')" :class="{active:mkdirIndex == -1}">全部</div>
                <div class="mkdir-item _display_flex" @click="switchMkdir(index, item)"  :class="{active:mkdirIndex == index}" v-for="(item, index) in mkdirList" :key="item">{{item}}</div>
                <div class="mkdir-item mkdir-item-add _display_flex" @click="addMkdir">新增分组</div>
            </div>
            <div class="upload-gather _display_flex">
                <!-- 头部 -->
                <div class="gather-cell _display_flex">
                    <div class="cell-left">
                        <el-dropdown  trigger="click" @command="moveMkdir" class="cell-dropdown">
                            <el-button type="primary" size="mini" >
                                移动至<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item :command="item" v-for="item in mkdirList" :key="item">{{item}}</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>

                        <el-button type="danger" size="mini" @click="delImgsMkdir">
                            <i class="el-icon-arrow-down el-icon-delete"></i>删除
                        </el-button>
                    </div>
                    <div class="cell-rigth">
                        <el-upload
                            :action="baseURL + 'upload'"
                            :show-file-list="false"
                            :data="mkdir"
                            :on-success="handleSuccess">
                            <el-button type="success" size="mini">
                                <i class="el-icon-arrow-down el-icon-upload"></i>上传图片
                            </el-button>
                        </el-upload>
                    </div>
                </div>
                <!-- 图片 -->
                <div class="gather-scroll _display_flex _scrollbar">
                    <div class="scroll-item" v-for="(item, index) in imgsList" :key="index">
                        <div class="item-box _display_flex" @click="getSelectImg(item.id, item.path)">
                            <el-image class="item-img" :src="path + item.path"></el-image>
                            <span class="item-name">{{item.filename}}</span>
                            <div class="item-select _display_flex" v-if="selectImgsIdArray.filter(v => v== item.id).length"><i class="el-icon-check"></i></div>
                        </div>
                    </div>
                    <div class="scroll-none _display_flex" v-if='!imgsList.length'>暂无图片</div>
                </div>
                <div class="gather-page _display_flex" v-if='imgsList.length'>
                    <el-pagination  background  layout="prev, pager, next" @current-change="currentChange" :current-page="page" :page-size="rows"  :total="total"></el-pagination>
                    <el-tag type="success">总共{{total}}条</el-tag>
                </div>
            </div>
		</section>
		<div class="button _display_flex" >
			<el-button type="success" size="mini" @click="onConfirm" >确定</el-button>
            <el-button size="mini" @click="onClose" >取消</el-button>
		</div>

        <!-- // 新增分组 -->
        <el-dialog top="30vh" :close-on-click-modal="false" title="请输入新分组名称" width="30%" :visible.sync="chilsShow" append-to-body>
            <div class="childs_input"><el-input v-model="mkdirInput"  ></el-input></div>
            <div class="button _display_flex" >
                <el-button type="success" size="mini" @click="onChildConfirm" >确定</el-button>
                <el-button size="mini" @click="onChildClose" >取消</el-button>
            </div>
        </el-dialog>
	</el-dialog>
</template>

<script>
	export default {
		name: 'Upload',
		title: '图片库',
		props: {
			show: {
				type: Boolean,
				default: true
            },
            leng: {
                type:[ String, Number],
                default: 9,
            },
			callback: {
				type: Function,
			}
        },
        computed: {
            // 上传的目录
            mkdir() {
                return {
                    mkdir: this.mkdirLabel
                }
            }
        },
		methods: {
            // 关闭图片库弹窗
			onClose() {
                this.show = false;
            },
            // 确定选择图片
            onConfirm() {
                if(!this.selectImgsIdArray.length){
                    this.$message({
                        type: 'info',
                        message: '请选择图片!'
                    });
                    return false
                }
                if(this.selectImgsIdArray.length > this.leng) {
                    this.$message({
                        type: 'info',
                        message: `请选择图片不超过${this.leng}张`
                    });
                    return false
                }
                let path_data = this.imgsList.filter(v => this.selectImgsIdArray.includes(v.id)).map(v => v.path)
                this.callback && this.callback(path_data)
                this.show = false;
                // this.selectImgsIdArray = []
            },
            // 新增分组/目录
            addMkdir() {
                this.chilsShow = true;
            },
            // 关闭新增分组
            onChildClose() {
                this.chilsShow = false;
            },
            // 确定新增分组
            onChildConfirm() {
                this.mkdirLabel = this.mkdirInput
				this.getAddMkdir()
            },
            // 切换分组
            switchMkdir(index, mkdir) {
                this.mkdirIndex = index
                this.mkdirLabel = index == -1 ? '' : mkdir
                this.getImgsList()
            },
            // 上传成功
            handleSuccess(res) {
                if(res.code === 200){
                    this.$message({
                        message: res.msg,
                        type: 'success',
                        duration:1000
                    });
                    this.imgsList = res.data.concat(this.imgsList)
                }else{
                    this.$message({
                        message: res.msg,
                        type: 'error',
                        duration:1000
                    });
                }
            },
            // 选择图片
            getSelectImg(id) {
                if(this.selectImgsIdArray.indexOf(id) > -1){
                    this.selectImgsIdArray.splice(this.selectImgsIdArray.indexOf(id), 1)
                }else{
                    this.selectImgsIdArray.push(id)
                }
            },
            // 删除图片和目录
            delImgsMkdir() {
                // 判断是否有图片，没有就提示删除分组
                if(!this.imgsList.length){
                    this.$confirm('此操作将永久删除该分组, 是否继续?', '删除分组', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.getDelMkdir()
                    }).catch(() => {});
                }else{                   
                    if(!this.selectImgsIdArray.length){
                        this.$message({
                            type: 'info',
                            message: '请选择图片!'
                        });
                        return false
                    }
                    this.$confirm('此操作将永久删除图片, 是否继续?', '删除图片', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.delImgs()
                    }).catch(() => {});
                }
            },
            // 移动目录/分组
            moveMkdir(event) {
                if(!this.selectImgsIdArray.length){
                    this.$message({
                        type: 'info',
                        message: '请选择图片!'
                    });
                    return false
                }
                this.getMoveMkdir(event)
            },
            // 页码
            currentChange(event) {
                this.page = event
                this.getImgsList()
            },
            // 图片列表
            async getImgsList() {
                let data = {
                    mkdir: this.mkdirLabel || -1,
                    page: this.page,
                    rows: this.rows
                }
                let res = await this.$Http.getImgsList({ data })
                this.imgsList = res.rows
                this.total = res.count
            },
            // 删除图片
            async delImgs() {
                let data = {
                    imgs_id: this.selectImgsIdArray
                }
                let res = await this.$Http.getDelImgs({ data })
                if(res){
                    // 清空选择图片
                    this.selectImgsIdArray = []
                    this.getImgsList()
                }
            },
            // 目录列表（分组列表）
            async getListMkdir() {
                let res = await this.$Http.getListMkdir()
                this.mkdirList = res
            },
            // 添加目录（新分组）
            async getAddMkdir() {
                let data = this.mkdir
                let res = await this.$Http.getAddMkdir({ data })
                if(res) {
                    this.mkdirList.push(res)
                    this.onChildClose()
                }
            },
            // 删除目录（新分组）
            async getDelMkdir() {
                let data = this.mkdir
                await this.$Http.getDelMkdir({ data })
                this.getListMkdir()
                
            },
            // 移动目录
            async  getMoveMkdir(mkdir) {
                const data = {
                    mkdir,
                    imgs_id: this.selectImgsIdArray
                }
                let res = await this.$Http.getMoveMkdir({ data })
                if(res){
                    // 清空选择图片
                    this.selectImgsIdArray = []
                    // 目录名称重新赋值
                    this.mkdirLabel = mkdir
                    this.mkdirIndex = this.mkdirList.indexOf(mkdir)
                    // 重新加载图片列表
                    this.getImgsList()
                }
            }
		},
		data() {
			return {
                chilsShow: false,
                total: 0,                   // 总条目数
                imgsList: [],               // 图片数据
                selectImgsIdArray: [],             // 选中的图片id
                page: 1,                    // 页码
                rows: 8,                    // 每页数目
                mkdirList: [],              // 目录列表
                mkdirIndex: -1,             // 目录索引
                mkdirLabel: '',             // 目录名称
                mkdirInput: '',    
			}
		},
		mounted() {
            this.getListMkdir()
            this.getImgsList()
		}
	}
</script>

<style lang="scss" scoped>
	.upload-box{
        width: 100%;
        height: 470px;
        margin-bottom: 10px;
        overflow: hidden;
        .upload-mkdir{
            width: 150px;
            padding-top: 30px;
            box-sizing: border-box;
            height: 100%;
            .mkdir-item{
                width: 100%;
                height: 38px;
                padding-left: 10px;
                box-sizing: border-box;
                font-size: $font-size-sm;
                cursor: pointer;
                &.active{
                    background: rgba($color: $bg-color-blue, $alpha: 0.4);
                    color: $text-color;
                }
            }
            .mkdir-item-add{
                color: $bg-color-blue;;
            }

        }
        .upload-gather{
            width: 100%;
            height: 100%;
            flex-direction: column;
            flex:  1;
            .gather-cell{
                width: 100%;
                height: 40px;
                padding:0 10px;
                box-sizing: border-box;
                justify-content: space-between;
                .cell-dropdown{
                    margin-right: 10px;
                }
            }
            .gather-scroll{
                width: 100%;
                height: 100%;
                padding-top:10px;
                box-sizing: border-box;
                flex: 1;
                overflow-y: scroll;
                flex-wrap: wrap;
                align-items: flex-start;
                .scroll-none{
                    width: 100%;
                    height: 100%;
                    justify-content: center;
                }
                .scroll-item{
                    width: 25%;
                    padding:0 10px;
                    margin-bottom: 10px;
                    box-sizing: border-box;
                    .item-box{
                        width: 100%;
                        padding:10px;
                        box-sizing: border-box;
                        border: solid 1px $border-color;
                        border-radius: 10px;
                        overflow: hidden;
                        flex-direction: column;
                        justify-content: center;
                        cursor: pointer;
                        position: relative;
                        &:hover{
                            border-color: $bg-color-blue;
                        }
                        .item-img{
                            width: 130px;
                            height: 130px;
                        }
                        .item-name{
                            width: 100%;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                            font-size: $font-size-xs;
                            margin-top: 10px;
                        }
                        .item-select{
                            position: absolute;
                            top: 10px;
                            right: 10px;
                            width: 20px;
                            height: 20px;
                            border-radius: 10px;
                            background: $bg-color-blue;
                            color: $text-color;
                            font-size: $font-size-sm;
                            justify-content: center;
                            cursor: pointer;
                        }
                    }
                }
            }
            .gather-page{
                width: 100%;
                margin-top: 10px;
                justify-content: flex-end;
            }
            
        }
    }
    /deep/.el-dialog__body{
        padding: 20px;
        padding-top: 0;
    }
    /deep/.el-dialog__header{
        background: $bg-color-grey;
    }
    .childs_input{
        padding: 20px 0;
    }
    .button{
        justify-content: flex-end;
    }
</style>